package util

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

type BaiduTranslateResponse struct {
	From        string `json:"from"`
	To          string `json:"to"`
	TransResult []struct {
		Src string `json:"src"`
		Dst string `json:"dst"`
	} `json:"trans_result"`
	ErrorCode string `json:"error_code"`
	ErrorMsg  string `json:"error_msg"`
}

func BaiduTranslate(apiKey, secretKey, q string, from, to string) (*BaiduTranslateResponse, error) {
	client := &http.Client{}

	v := url.Values{}
	v.Set("q", q)
	v.Set("from", from)
	v.Set("to", to)
	v.Set("appid", apiKey)
	v.Set("salt", "1631503886")
	sign := getSign(apiKey, secretKey, q, "1631503886")
	fmt.Println(sign)
	v.Set("sign", getSign(apiKey, secretKey, q, "1631503886"))

	urlStr := "http://api.fanyi.baidu.com/api/trans/vip/translate?" + v.Encode()

	req, err := http.NewRequest("GET", urlStr, nil)
	if err != nil {
		return nil, err
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	fmt.Println(string(body))

	var result BaiduTranslateResponse
	err = json.Unmarshal(body, &result)
	if err != nil {
		return nil, err
	}

	return &result, nil
}

func getSign(apiKey, secretKey, q, salt string) string {
	str := apiKey + q + salt + secretKey

	hash := md5.New()

	// 写入数据到哈希对象
	_, err := io.WriteString(hash, str)
	if err != nil {
		fmt.Println("Error writing string to hash:", err)
		return ""
	}

	// 计算哈希值
	sum := hash.Sum(nil)

	return hex.EncodeToString(sum) // 这里需要引入md5库，并调用其Sum方法
}

func Translate(q string, from string, to string) string {
	time.Sleep(time.Second)
	apiKey := "20181105000230075"
	secretKey := "NnNaWlJjZ2696l31dJMb"

	result, err := BaiduTranslate(apiKey, secretKey, q, from, to)
	if err != nil {
		fmt.Println("Error:", err)
		return ""
	}
	if result.ErrorCode != "" {
		fmt.Println("Error:", result.ErrorMsg)
		return ""
	}
	return result.TransResult[0].Dst
}
